<?php
namespace app\lib;

use think\Db;
use app\model\UserBill as UserBillModel;
use app\model\Bill as BillModel;
use app\model\User as UserModel;
use app\model\Order as OrderModel;

use app\lib\BceSignService as BceSignService;

class BceApi 
{
    public $host;

    public function __construct() {
        $this->host = config('config.baiduyun.host');
    }

    public function getAuthorization($method,$uri,$query=[]){
        $timestamp = gmdate('Y-m-d\TH:i:s\Z');
        $headers = [
            'host'=>$this->host
        ];

        $signer = new BceSignService();
        // 生成Authorization头
        $authHeader = $signer->generateAuthHeader(
            $method,$uri,$query,$headers,$timestamp
        );

        return [
            'timestamp'=>$timestamp,
            'authorization'=>$authHeader
        ];
    }

    public function getApiHeader($method,$uri,$query=[]){
        $authorization = $this->getAuthorization($method,$uri,$query);
        $header = [
            'Host:'.$this->host,
            'x-bce-date:'.$authorization['timestamp'],
            'Authorization:'.$authorization['authorization']
        ];
        if ($method == 'POST') {
            $header[] = 'content-type:application/json';
        }

        return $header;
    }






    public function resetUserQuota(){
        $list = Db::name('user')->where([
            ['total_recharge','>',0],
            ['is_quota','=',1]
        ])->select();
        foreach ($list as $k => $vo) {
            $this->SetResellerUserQuota($vo['pk']);
        }
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return BssOpenApi Client
     */
    public static function createClient($accessKeyId='',$accessKeySecret=''){
        $config = config('config.alibabacloud');
        if (empty($accessKeyId)) {
            $accessKeyId = $config['keyId'];
        }
        if (empty($accessKeySecret)) {
            $accessKeySecret = $config['keySecret'];
        }
        $aliconfig = new Config([
            // 您的AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 您的AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $aliconfig->endpoint = "business.aliyuncs.com";
        return new BssOpenApi($aliconfig);
    }

    // 使用AK&SK初始化账号Client
    public static function accessKeyClient($accessKeyId='',$accessKeySecret=''){
        $config = config('config.alibabacloud');
        if (empty($accessKeyId)) {
            $accessKeyId = $config['keyId'];
        }
        if (empty($accessKeySecret)) {
            $accessKeySecret = $config['keySecret'];
        }
        $regionid = 'cn-beijing';

        AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)->regionId($regionid)->asDefaultClient();
    }

    /**
     * ===================================================================================
     * ======================================角色扮演======================================
     */
    
    // 扮演RAM角色
    public function AssumeRole($ower_id){
        try {
            $user = UserModel::field('id,pk,role_name,mobile')->where('pk',$ower_id)->find();
            if (empty($user)) {
                return ['status'=>0,'msg'=>'用户不存在'];
            }
            $config = config('config.aliasssume');
            $aliconfig = new Config([
                "accessKeyId" => $config['keyId'],
                "accessKeySecret" => $config['keySecret']
            ]);
            // 访问的域名
            $aliconfig->endpoint = "sts.cn-beijing.aliyuncs.com";
            $client = new Sts($aliconfig);
            $assumeRoleRequest = new AssumeRoleRequest([
                "roleArn" => "acs:ram::".$user['pk'].":role/".$user['role_name'],
                "roleSessionName" => 'user_'.$user['mobile']
            ]);

            $result = $client->assumeRole($assumeRoleRequest);
            $result = $result->body->toMap();
            return ['status'=>1,'data'=>[
                'AccessKeyId'=>$result['Credentials']['AccessKeyId'],
                'AccessKeySecret'=>$result['Credentials']['AccessKeySecret'],
                'SecurityToken'=>$result['Credentials']['SecurityToken']
            ]];
        } catch (ClientException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        } catch (ServerException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }

    // 获取登录令牌
    public function GetSigninToken($ower_id){
        $this->host = 'sts.bj.baidubce.com';
        $uri = '/v1/signinSecurityToken';
        $method = 'POST';

        $options = [
          'userId' => $ower_id,
        ];

        try {
            $url = 'http://'.$this->host.$uri.'?'.http_build_query($options);
            $header = $this->getApiHeader($method,$uri,$options);
            $result = httpRequest($url,'',$method,$header);
            $result = json_decode($result,true);

            if (!empty($result['sessionToken'])) {
                $result = ['status'=>1,'data'=>$result['sessionToken']];
            }else{
                $result = ['status'=>0,'msg'=>$result['message']];
            }
        } catch (ClientException $e) {
            $result = ['status'=>0,'msg'=>$e->getMessage()];
        } catch (ServerException $e) {
            $result = ['status'=>0,'msg'=>$e->getMessage()];
        }

        return $result;
    }

    // 获取登录链接
    public function GetSigninUrl($id,$redirect_url){
        $uinfo = Db::name('user')->where('id',$id)->find();
        if ($uinfo['status'] == 0) {
            return apiErrorResult('用户需先同步');
        }

        $token = $this->GetSigninToken($uinfo['pk']);
        if ($token['status'] == 0) {
            return apiErrorResult($token['message']);
        }
        $token = urlencode($token['data']);

        $this->host = 'console.vcp.baidu.com';
        $uri = '/api/loginvcp/login/securitytoken?redirectUrl='.urlencode($redirect_url).'&serviceType=bcc&signinSecurityToken='.$token;
        $method = 'GET';
        $url = 'https://'.$this->host.$uri;


        return ['status'=>1,'data'=>$url];
    }

    /**
     * ===================================================================================
     * ======================================账号管理======================================
     */

    // 创建平行账号
    public function CreateAgAccount($id){
        $uinfo = Db::name('user')->where('id',$id)->find();
        if ($uinfo['status'] != 0) {
            return apiErrorResult('当前用户已同步');
        }

        $uri = '/v1/vs/account';
        $method = 'POST';

        $options = [
          'name' => 'uuid_'.$uinfo['id'],
          'email' => $uinfo['email'],
          'mobilePhone' => $uinfo['mobile'],
          'accountType' => $uinfo['account_attr'],
        ];
        if ($options['accountType'] == 1) {
            $options['company'] = $uinfo['enterprise'];
        }
        $options = delEmpty($options);

        try {
            $url = 'http://'.$this->host.$uri;
            $header = $this->getApiHeader($method,$uri);
            $result = httpRequest($url,json_encode($options),$method,$header);
            $result = json_decode($result,true);
            if (empty($result['userId'])) {
                return apiErrorResult($result['message']);
            }
            // 将userId保存
            Db::name('user')->where('id',$id)->update([
                'status'=>1,
                'pk'=>$result['userId'],
                'utime'=>time()
            ]);

            return apiSuccessResult('同步成功');
        } catch (ClientException $e) {
            return apiErrorResult($e->getMessage());
        } catch (ServerException $e) {
            return apiErrorResult($e->getMessage());
        }
    }

    // 查找虚商客户账号信息
    public function GetCustomerAccountInfo($ower_id){
        try {
            $uri = '/v1/vs/account/'.$ower_id;
            $method = 'GET';
            
            $url = 'http://'.$this->host.$uri;
            $header = $this->getApiHeader($method,$uri);
            $result = httpRequest($url,'',$method,$header);

            return $result;
        } catch (ClientException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        } catch (ServerException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }

    // 实名认证
    public function AddIdentityCertifiedForBidUser($id){
        $uinfo = Db::name('user')->where('id',$id)->find();
        if ($uinfo['status'] == 0) {
            return apiErrorResult('用户需先同步');
        }

        $token = $this->GetSigninToken($uinfo['pk']);
        if ($token['status'] == 0) {
            return apiErrorResult($token['message']);
        }
        $token = urlencode($token['data']);
        $redirect_url = urlencode('https://console.vcp.baidu.com/qualify/#/qualify/index');

        $url = 'https://console.vcp.baidu.com/api/loginvcp/login/securitytoken?redirectUrl='.$redirect_url.'&signinSecurityToken='.$token;

        return ['status'=>1,'data'=>$url];
    }

    // 查询实名认证
    public function SearchIdentityCertifiedForBidUser($ower_id){
        try {
            $this->host = 'qualify.baidubce.com';
            $uri = '/v1/getQualifyInfo';
            $method = 'GET';
            $query = ['accountId'=>$ower_id];
            
            $url = 'http://'.$this->host.$uri.'?'.http_build_query($query);
            $header = $this->getApiHeader($method,$uri,$query);
            $result = httpRequest($url,'',$method,$header);
            $result = json_decode($result,true);

            return ['status'=>1,'data'=>$result];
        } catch (ClientException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        } catch (ServerException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }

    // 删除实名认证信息
    public function RemoveIdentityCertifiedForBidUser($id=''){
        $uinfo = Db::name('user')->where('id',$id)->find();
        if ($uinfo['status'] != 2) {
            return apiErrorResult('用户暂未实名');
        }

        $options = [
            'BidType' => 'LIGHTWEIGHT',
            'PK' => $uinfo['pk']
        ];

        try {
            self::accessKeyClient(); // 使用AK&SK初始化账号Client
            $result = AlibabaCloud::rpc()
                ->version('2015-04-08')
                ->action('RemoveIdentityCertifiedForBidUser')
                ->method('POST')
                ->host('crm-cn-hangzhou.aliyuncs.com')
                ->options(['query' => $options])
                ->request();
            $result = $result->toArray();
            // 认证成功只会返回RequestId，如果有Code说明有错误
            if (isset($result['Code'])) {
                return apiErrorResult($result['Message']);
            }
            Db::name('user')->where('id',$id)->update([
                'status'=>1,
                'utime'=>time()
            ]);
            return apiSuccessResult('删除实名认证成功');
        } catch (ClientException $e) {
            return apiErrorResult($e->getMessage());
        } catch (ServerException $e) {
            return apiErrorResult($e->getMessage());
        }
    }

    /**
     * ===================================================================================
     * ======================================预算管理======================================
     */

    // 查询当前可用配额余额信息
    public function QueryResellerAvailableQuota($ower_id){
        $client = self::createClient();
        $queryResellerAvailableQuotaRequest = new QueryResellerAvailableQuotaRequest([
            'ownerId'=>$ower_id
        ]);
        // 复制代码运行请自行打印 API 的返回值
        $result = $client->queryResellerAvailableQuota($queryResellerAvailableQuotaRequest);
        $result = $result->body->toMap();
        return $result;
    }

    // 创建用户 Quota 配额账本
    // public function CreateResellerUserQuota($id){
    //     $uinfo = Db::name('user')->where('id',$id)->find();
    //     if ($uinfo['status'] == 0) {
    //         return apiErrorResult('用户需先同步');
    //     }
    //     if ($uinfo['is_quota'] == 1) {
    //         // return apiErrorResult('当前用户已有账本');
    //     }

    //     $client = self::createClient();
    //     $createResellerUserQuotaRequest = new CreateResellerUserQuotaRequest([
    //         'ownerId'=>$uinfo['pk'],
    //         "amount" => '100',
    //         "currency" => "CNY"
    //     ]);
     
    //     $result = $client->createResellerUserQuota($createResellerUserQuotaRequest);
    //     $result = $result->body->toMap();
    //     dump($result);die;

   
    //     try {
    //         self::accessKeyClient(); // 使用AK&SK初始化账号Client
    //         $result = AlibabaCloud::rpc()
    //             ->product('BssOpenApi')
    //             // ->scheme('https') // https | http
    //             ->version('2017-12-14')
    //             ->action('CreateResellerUserQuota')
    //             ->method('POST')
    //             ->host('business.aliyuncs.com')
    //             ->options(['query' => $options])
    //             ->request();

    //         $result = $result->toArray();
    //         if (!$result['Success']) {
    //             return apiErrorResult($result['Message']);
    //         }
    //         Db::name('user')->where('id',$id)->update([
    //             'is_quota'=>1,
    //             'utime'=>time()
    //         ]);
    //         return apiSuccessResult('账本创建成功');
    //     } catch (ClientException $e) {
    //         return apiErrorResult($e->getMessage());
    //     } catch (ServerException $e) {
    //         return apiErrorResult($e->getMessage());
    //     }
    // }
    public function CreateResellerUserQuota($ower_id){
        $uinfo = UserModel::where('pk',$ower_id)->find();
        // if ($uinfo['status'] != 2) {
        //     return apiErrorResult('用户需先实名');
        // }
        if ($uinfo['is_quota'] == 1) {
            return apiErrorResult('当前用户已有账本');
        }

        $options = [
            'OwnerId' => $uinfo['pk'],
            'Amount' => round($uinfo['total_recharge']/$uinfo['total_discount'],2),
            'Currency' => 'CNY'
        ];

        try {
            self::accessKeyClient(); // 使用AK&SK初始化账号Client
            $result = AlibabaCloud::rpc()
                ->product('BssOpenApi')
                // ->scheme('https') // https | http
                ->version('2017-12-14')
                ->action('CreateResellerUserQuota')
                ->method('POST')
                ->host('business.aliyuncs.com')
                ->options(['query' => $options])
                ->request();

            $result = $result->toArray();
            if (!$result['Success']) {
                return apiErrorResult($result['Message']);
            }
            Db::name('user')->where('id',$uinfo['id'])->update([
                'is_quota'=>1,
                'bill_date'=>date('Ymd'),
                'utime'=>time()
            ]);
            // return apiSuccessResult('账本创建成功');
            return ['status'=>1];
        } catch (ClientException $e) {
            // return apiErrorResult($e->getMessage());
            return ['status'=>0,'msg'=>$e->getMessage()];
        } catch (ServerException $e) {
            // return apiErrorResult($e->getMessage());
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }

    // 设置用户 Quota
    public function SetResellerUserQuota($ower_id){
        try {
            $uinfo = UserModel::field('id,pk,balance,total_recharge,total_discount,status,is_quota')->where('pk',$ower_id)->find();
            if ($uinfo['status'] == 0) {
                return apiErrorResult('用户需先同步');
            }
            if ($uinfo['is_quota'] == 0) {
                return apiErrorResult('用户需先创建账本');
            }
            $client = self::createClient();
            $amount = round($uinfo['total_recharge']/$uinfo['total_discount'],2);
            $setResellerUserQuotaRequest = new SetResellerUserQuotaRequest([
                'ownerId'=>$uinfo['pk'],
                "amount" => $amount < 0 ? 0 : $amount,
                "currency" => "CNY"
            ]);
            // dump([
            //     'ownerId'=>$uinfo['pk'],
            //     "amount" => $uinfo['balance'] < 0 ? 0 : $uinfo['balance'],
            //     "currency" => "CNY"
            // ]);die;
      
            $result = $client->setResellerUserQuota($setResellerUserQuotaRequest);
            $result = $result->body->toMap();
            if (!$result['Success']) {
                return ['status'=>0,'msg'=>$result['Message']];
            }
            return ['status'=>1];
        } catch (ClientException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        } catch (ServerException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }

    // 实名认证
    public function GenerateAliyunBidCertWaysUrl($ower_id){
        $uinfo = Db::name('user')->where('pk',$ower_id)->find();
        if ($uinfo['status'] == 0) {
            return apiErrorResult('用户需先同步');
        }

        $options = [
            'BidType' => 'LIGHTWEIGHT',
            'AliyunPk' => $uinfo['pk'],
            'Platform'=>'pc',
            'SubjectType'=>'all',
            'Source'=>'BID',
            'IsOpenApp'=>true,
            'IsMobile'=>true,
        ];

        try {
            self::accessKeyClient(); // 使用AK&SK初始化账号Client
            $result = AlibabaCloud::rpc()
                      ->version('2015-07-01')
                      ->action('GenerateAliyunBidCertWaysUrl')
                      ->method('POST')
                      ->host('aas.aliyuncs.com')
                      ->options(['query' => $options])
                      ->request();
            $result = $result->toArray();
            // 认证成功只会返回RequestId，如果有Code说明有错误
            if (isset($result['Code'])) {
                return apiErrorResult($result['Message']);
            }
            
            return apiSuccessResult('获取认证链接成功',['url'=>$result['Data']]);
        } catch (ClientException $e) {
            return apiErrorResult($e->getMessage());
        } catch (ServerException $e) {
            // 如果返回的错误是已实名认证，则视为认证成功
            if (strpos($e->getMessage(), 'Already Certified') !== false) {
                return ['status'=>2,'msg'=>$e->getMessage()];
            }else{
                return apiErrorResult($e->getMessage());    
            }
        }
    }

    // 查询虚商客户实名认证信息
    public function QueryBidUserCertifiedInfo($ower_id){
        $uinfo = Db::name('user')->where('pk',$ower_id)->find();
        if ($uinfo['status'] == 0) {
            return apiErrorResult('用户需先同步');
        }

        $options = [
            'BidType' => 'LIGHTWEIGHT',
            'PK' => $uinfo['pk']
        ];

        try {
            self::accessKeyClient(); // 使用AK&SK初始化账号Client
            $result = AlibabaCloud::rpc()
                      ->version('2015-04-08')
                      ->action('QueryBidUserCertifiedInfo')
                      ->method('POST')
                      ->host('crm-cn-hangzhou.aliyuncs.com')
                      ->options(['query' => $options])
                      ->request();
            $result = $result->toArray();
            return apiSuccessResult('获取认证信息',json_decode($result['Result'],true));
        } catch (ClientException $e) {
            dump($e->getMessage());die;
            return apiErrorResult($e->getMessage());
        } catch (ServerException $e) {
            dump($e->getMessage());die;
            return apiErrorResult($e->getMessage());
        }
    }

    // 设置托管、冻结状态
    public function SetResellerUserStatus($ower_id,$business_type,$status){
        try {
            $client = self::createClient();
            $setResellerUserStatusRequest = new SetResellerUserStatusRequest([
                'ownerId'=>$ower_id,
                "status" => $status,
                "businessType" => $business_type
            ]);
            $result = $client->setResellerUserStatus($setResellerUserStatusRequest);
            $result = $result->body->toMap();
            if (!$result['Success']) {
                return ['status'=>0,'msg'=>$result['Message']];
            }
            return ['status'=>1];
        } catch (ClientException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        } catch (ServerException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }

    // 用户quota消费抵扣
    // amount > 0 减少阿里侧余额，< 0 增加阿里侧余额
    public function ChangeResellerConsumeAmount($ower_id,$amount,$bill_sn){
        try {
            $client = self::createClient();
            $changeResellerConsumeAmountRequest = new ChangeResellerConsumeAmountRequest([
                'ownerId'=>$ower_id,
                "adjustType" => $amount > 0 ? "increase" : "decrease",
                "amount" => abs($amount),
                "currency" => "CNY",
                "businessType" => "quota_amount_adjust",
                "outBizId" => $bill_sn,
                "source" => "dellidc"
            ]);
            $runtime = new RuntimeOptions([]);
            // 复制代码运行请自行打印 API 的返回值
            $result = $client->changeResellerConsumeAmountWithOptions($changeResellerConsumeAmountRequest, $runtime);
            $result = $result->body->toMap();
            if (!$result['Success']) {
                return ['status'=>0,'msg'=>$result['Message']];
            }
            return ['status'=>1];
        } catch (ClientException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        } catch (ServerException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }

    /**
     * ===================================================================================
     * ======================================产品信息======================================
     */

    // 查询阿里云产品信息
    public function QueryProductList(){
        $client = self::createClient();
        $queryProductListRequest = new QueryProductListRequest([
            "pageNum" => 1,
            "pageSize" => 1000
        ]);
        // 复制代码运行请自行打印 API 的返回值
        $result = $client->queryProductList($queryProductListRequest);
        $result = $result->body->toMap();
        dump($result);die;
        if ($result['Code'] == 'Success') {
            $save_data = [];
            // dump($result['Data']['ProductList']['Product']);die;
            foreach ($result['Data']['ProductList']['Product'] as $k => $vo) {
                $code = $vo['ProductCode'];
                if ( empty($save_data[$code]) ) {

                    $save_data[$code] = [
                        'name'=>preg_replace('/(（|\().*?(）|\))/', '', $vo['ProductName']),
                        'code'=>$code,
                        'type'=>$vo['ProductType'],
                        'ctime'=>time()
                    ];
                }
            }
            if (!empty($save_data)) {
                Db::name('product')->insertAll($save_data);
            }
            
        }
    }

    /**
     * ===================================================================================
     * ======================================订单查询======================================
     */
    // 查询指定 uuid 的订单详情
    public function GetOrdersByUuid($uuids,$ower_id){
        $this->host = 'billing.baidubce.com';
        $uri = '/v1/order/getByUuid';
        $method = 'POST';

        $options = [
          'uuids' => $uuids,
          'queryAccountId' => $ower_id
        ];

        try {
            $url = 'http://'.$this->host.$uri;
            $header = $this->getApiHeader($method,$uri);
            $result = httpRequest($url,json_encode($options),$method,$header);
            $result = json_decode($result,true);
            if (empty($result['orders'])) {
                return apiErrorResult('no data');
            }

            return ['status'=>1,'data'=>$result['orders']];
        } catch (ClientException $e) {
            return apiErrorResult($e->getMessage());
        } catch (ServerException $e) {
            return apiErrorResult($e->getMessage());
        }
    }

    public function payOrder($uuid,$ower_id){
        $oinfo = $this->GetOrdersByUuid([$uuid],$ower_id);
        if ($oinfo['status'] == 0) {
            return ['status'=>0];
        }
        $order_status = getBceOrderStatus($oinfo['data'][0]['status']);
        if ($order_status == 0) {
            // $balance = Db::name('user')->where('pk',$ower_id)->value('balance');
            // if ($balance <= 0) {
            //     return apiErrorResult('用户余额不足');
            // }

            // $data = Db::name('order')->where('order_uuid',$uuid)->find();
            // if ($balance < $data['platform_amount']) {
            //     return apiErrorResult('用户余额不足，当前余额：'.$balance.'，UID：'.$ower_id);   
            // }

            $this->host = 'billing.baidubce.com';
            $uri = '/v1/order/pay';
            $method = 'POST';

            $options = [
              'orderId' => $uuid,
              'queryAccountId' => $ower_id
            ];

            try {
                $url = 'http://'.$this->host.$uri;
                $header = $this->getApiHeader($method,$uri);
                $result = httpRequest($url,json_encode($options),$method,$header);
                // $result = '{"success":true}';
                Db::name('test')->insert(['content'=>'-------------------------------']);
                Db::name('test')->insert(['content'=>json_encode($options)]);

                Db::name('test')->insert(['content'=>$result]);
                $result = json_decode($result,true);

                if ( $result['success'] ) {
                    return ['status'=>1];
                }else{
                    return apiErrorResult($result['message']);
                }
            } catch (ClientException $e) {
                return apiErrorResult($e->getMessage());
            } catch (ServerException $e) {
                return apiErrorResult($e->getMessage());
            }
        }else{
            return ['status'=>1];
        }
    }


    // 取消订单
    public function cancelOrders($uuid,$ower_id){
        $data = Db::name('order')->where('order_uuid',$uuid)->select();
        if ($data['status'] != 0) {
            return apiErrorResult('订单当前状态无法取消');
        }

        $this->host = 'billing.baidubce.com';
        $uri = '/v1/order/cancel';
        $method = 'POST';

        $options = [
          'orderIds' => [$uuid],
          'queryAccountId' => $ower_id
        ];

        try {
            $url = 'http://'.$this->host.$uri;
            $header = $this->getApiHeader($method,$uri);
            $result = httpRequest($url,json_encode($options),$method,$header);
            // $result = '{"success":true}';
            $result = json_decode($result,true);

            if ( $result['success'] ) {
                return ['status'=>1];
            }else{
                return apiErrorResult($result['message']);
            }
        } catch (ClientException $e) {
            return apiErrorResult($e->getMessage());
        } catch (ServerException $e) {
            return apiErrorResult($e->getMessage());
        }
    }

    // 订单查询
    public function GetOrderList($page_no = 1,$ower_id='',$start_time='',$end_time=''){
        $this->host = 'billing.baidubce.com';
        $uri = '/v1/order/list';
        $method = 'POST';
        
        if (empty($start_time)) {
            $start_time = date('Y-m-d\T00:00:00\Z',strtotime('-1 days'));
        }
        if (empty($end_time)) {
            $end_time = date('Y-m-d\T23:59:59\Z');
        }

        $options = [
          'startTime' => $start_time,
          'endTime' => $end_time,
          'pageNo' => $page_no,
          'pageSize' => 1000
        ];
        if (!empty($ower_id)) {
            $options['queryAccountId'] = $ower_id;
        }

        try {
            $url = 'http://'.$this->host.$uri;
            $header = $this->getApiHeader($method,$uri);
            $result = httpRequest($url,json_encode($options,JSON_UNESCAPED_UNICODE),$method,$header);
            $result = json_decode($result,true);

            return ['status'=>1,'data'=>$result];
        } catch (ClientException $e) {
            return apiErrorResult($e->getMessage());
        } catch (ServerException $e) {
            return apiErrorResult($e->getMessage());
        }
    }

    // 计费项账单(小时粒度)
    public function GetResourceChargeItemBillList($bill_date,$page_no = 1,$ower_id=''){
        $this->host = 'billing.baidubce.com';
        $uri = '/v1/bill/resource/chargeitem';
        $method = 'POST';

        $options = [
          'beginTime' => $bill_date,
          'endTime' => $bill_date,
          'pageNo' => $page_no,
          'pageSize' => 100
        ];
        if (!empty($ower_id)) {
            $options['queryAccountId'] = $ower_id;
        }

        try {
            $url = 'http://'.$this->host.$uri;
            $header = $this->getApiHeader($method,$uri);
            $result = httpRequest($url,json_encode($options),$method,$header);
            $result = json_decode($result,true);

            return ['status'=>1,'data'=>$result];
        } catch (ClientException $e) {
            return apiErrorResult($e->getMessage());
        } catch (ServerException $e) {
            return apiErrorResult($e->getMessage());
        }
    }

 

   
}
